package com.proscenic.ops.mp.service.impl;

import com.alibaba.fastjson.JSON;
import com.proscenic.ops.mp.dto.PostParam;
import com.proscenic.ops.mp.dto.VerifyParam;
import com.proscenic.ops.mp.service.PortalService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @version 1.0
 * created by chenxin on 2021/11/1 16:11
 */
@Slf4j
@Service
public class PortalServiceImpl implements PortalService {
    @Resource
    private WxMpService wxMpService;
    @Resource(name = "mpRouter")
    private WxMpMessageRouter wxMpMessageRouter;

    @Override
    public String verify(VerifyParam param) {
        if(wxMpService.checkSignature(param.getTimestamp(), param.getNonce(), param.getSignature())){
            //校验通过
            return param.getEchostr();
        }

        return "非法请求";
    }

    @Override
    public String post(PostParam param, String body) {
        log.info("param:" + JSON.toJSONString(param));
        log.info("body:" + body);
        WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(body);
        WxMpXmlOutMessage outMessage = wxMpMessageRouter.route(inMessage);

        if(outMessage == null){
            return "";
        }

        return outMessage.toXml();
    }
}
